#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>

int main(){
    /*1.创建套接字*/
    int sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if(sockfd < 0){
        perror("socket");
        return 0;
    }
    /*2.发起连接*/
    struct sockaddr_in svr_addr;
    svr_addr.sin_family = AF_INET;
    svr_addr.sin_port = htons(38989);
    svr_addr.sin_addr.s_addr = inet_addr("120.24.190.245");
    int ret = connect(sockfd, (struct sockaddr*)&svr_addr, sizeof(svr_addr));
    if(ret < 0){
        perror("connect");
        return 0;
    }
    while(1){
        /*3.收发数据*/
        char buf[1024] = {0};
        printf("please enter: ");
        fflush(stdout);

        std::cin >> buf;
        //strcpy(buf, "i am client");
        send(sockfd, buf, strlen(buf), 0);

        memset(buf, '\0', 1024);

        ssize_t recv_size  = recv(sockfd, buf, sizeof(buf) - 1, 0);
        if(recv_size < 0){
            perror("recv");
        }else if(recv_size == 0){
            close(sockfd);
            return 0;
        }else{
            printf("server say: %s\n", buf);
        }
        sleep(1);
    }

    /*4.关闭套接字*/
    close(sockfd);
    return 0;
}
